package com.tsoj.tsojjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.tsoj.common.ErrorCode;
import com.tsoj.exception.BusinessException;
import com.tsoj.model.codesandbox.ExecuteCodeRequest;
import com.tsoj.model.codesandbox.ExecuteCodeResponse;
import com.tsoj.model.codesandbox.JudgeInfo;
import com.tsoj.model.dto.question.JudgeCase;
import com.tsoj.model.enums.QuestionSubmitStatusEnum;
import com.tsoj.model.po.Question;

import com.tsoj.model.po.QuestionSubmit;
import com.tsoj.tsojjudgeservice.judge.codesandbox.CodeSandbox;
import com.tsoj.tsojjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.tsoj.tsojjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.tsoj.tsojjudgeservice.judge.strategy.JudgeContext;
import com.tsoj.tsojserviceclient.service.QuestionFeignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 判题逻辑
 */
@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionFeignClient questionFeignClient;
    @Value("${CodeSandbox.type}")
    private String type;
    @Resource
    private JudgeManger judgeManger;
    /**
     * 判题服务实现
     * @param questionSubmitId
     * @return
     */
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //1.传入题目提交id，获取对应题目，提交信息
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目提交不存在");
        }

        Long id = questionSubmit.getId();
        Long questionid = questionSubmit.getQuestionid();
        Long userid = questionSubmit.getUserid();

        Question question = questionFeignClient.getQuestionById(questionid);
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        //2.如果题目提交状态不为等待中,就不用重复执行
        if(!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "正在判题中");
        }
        //3.更改判题的状态为判题中,防止重复执行
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        questionSubmitUpdate.setId(id);
        boolean b = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if(!b){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新题目提交状态失败");
        }

        //4.调用代码沙箱执行判题，获取执行结果
        //用指定类型代码沙箱 工厂模式 todo 亮点
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        //用代理模式 实现加入日志的增强 todo 亮点
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        //获取输入用例
        String judecaseStr = question.getJudgecase();
        //获取判题配置
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judecaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        //调用代码沙箱
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);

        List<String> outputList = executeCodeResponse.getOutputList();
        //5.设置判题上下文信息，封装进行调用判题接口,判断回答是否正确
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        //进行判题
        JudgeInfo judgeInfo = judgeManger.doJudge(judgeContext);
        
        //6.更新判题信息
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(id);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeinfo(JSONUtil.toJsonStr(judgeInfo));
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新题目提交状态失败");
        }
        QuestionSubmit questionsubmitResponse = questionFeignClient.getQuestionSubmitById(id);
        return questionsubmitResponse;
    }
}
